/**
 * Created by hjqi on 2016/6/02.
 */
module.controller('StorageListController',
  function ($scope, $rootScope, $cookies, $q, $window, $stateParams, $uibModal, $state, storageService, k8sService, VolMgrConf, netTesting, svcCommonService,$mdDialog,radialIndicatorInstance,$filter) {
    $scope.indicatorOption = {
      radius: 18,
      percentage: true,
      barColor: {
        0: '#11CB77',
        60: '#F9BF3F',
        100: '#FF9191'
      },
      barWidth: 4,
      fontSize: 12,
      roundCorner: true,
      fontWeight: 400
    };
    $scope.indicatorOption2 = {
      radius: 18,
      percentage: true,
      barColor: {
        0: '#11CB77',
        60: '#F9BF3F',
        100: '#FF9191'
      },
      barWidth: 4,
      fontSize: 12,
      roundCorner: true,
      fontWeight: 400,
      initValue: 10
    };

    $scope.showAdvanc = function (e,ev) {
        e.stopPropagation();
      $mdDialog.show({
        controller: 'StorageDeleteController',
        templateUrl: 'storageDel.html',
        parent: angular.element(document.body),
        targetEvent: e,
        clickOutsideToClose: true,
        fullscreen: true,// Only for -xs, -sm breakpoints.
          locals: {
              params: {
                  ev: ev,
                  storages:$scope.storages
              }
          }
      })
    };
    $scope.showDetailModal = function (ev) {
      $mdDialog.show({
        controller:'StorageDetailModalController',
        templateUrl: 'storageDetailModal.html',
        parent: angular.element(document.body),
        targetEvent: ev,
        clickOutsideToClose: true,
        fullscreen: true, // Only for -xs, -sm breakpoints.
          locals: {
              params: {
                  ev: ev
              }
          }
      })
        .then(function (isInstall) {

          if (isInstall) {
            //TODO
            // install storage service in remote cluaster

          }

          //$scope.status = 'You said the information was "' + answer + '".';
        }, function () {

        });
    };

    $scope.storages = [];
    var loopTO = undefined;
    var isClose = false;
    $scope.templateUrl = '/template/cp/ngbusytemplate.html';
    var loadData = function () {

      storageService.getStoragelist().then(function (ret) {
            if (ret.ret === true) {
                var rets = ret.data;
                $scope.storages=rets.slice();
            }
             else {
                alertify.error("load storage list error:" + ret.error);
            }
        }, function (err) {
            alertify.error("load storage list error:" + err.error);
        })

    }

    loadData();
    $scope.$watchCollection('storages', function (newvalue, oldvalue) {
      $scope.storageslist = newvalue.slice();
    });

    $scope.currentPageStorages = [];
    $scope.currentPage = 1;
    $scope.numPerPage = 10;
    $scope.searchPageHide=false;
    $scope.searchText="";
    $scope.$watch("storageslist + currentPage", function () {
      var begin = (($scope.currentPage - 1) * $scope.numPerPage)
        , end = begin + $scope.numPerPage;
      var _oral_list = $scope.storageslist.slice(begin, end);
        if ($scope.storageslist) {
          if($scope.searchText == ""){
            $scope.currentPageStorages = _formatStorageList(_oral_list);
          }else{
            var all_oral_list=$filter('filter')($scope.storageslist, {'name': $scope.searchText})
            $scope.currentPageStorages =_formatStorageList(all_oral_list) ;
          }
        }

      $scope.searchClick=function () {
        /*       $scope.currentPageServices=utilService.searchObj(currentServices,$scope.services,$scope.searchText,'id')*/

        if ($scope.searchText == "") {
          $scope.searchPageHide=false;
          $scope.currentPageStorages = _formatStorageList(_oral_list);
        } else {
          $scope.searchPageHide=true;
          var all_oral_list=$filter('filter')($scope.storageslist, {'name': $scope.searchText})
          $scope.currentPageStorages =_formatStorageList(all_oral_list) ;
        }
      }
    });

    $scope.createVolumn = function () {

       $mdDialog.show({
          controller: 'StorageCreateModalController',
         templateUrl: 'template/cp/storageCreateModal.html',

          parent: angular.element(document.body),
          clickOutsideToClose: true,
          fullscreen: true // Only for -xs, -sm breakpoints.
        })
          .then(function (data) {

            $scope.storages.push(data);


            //$scope.status = 'You said the information was "' + answer + '".';
          }, function () {
            console.log('Modal dismissed at: ' + new Date());
          });
      /*var modalInstance = $uibModal.open({
        animation: true,
        templateUrl: 'template/cp/storageCreateModal.html',
        controller: 'StorageCreateModalController'
      });

      modalInstance.result.then(function (addItem) {
        $scope.storages.push(addItem);
      }, function () {
        console.log('Modal dismissed at: ' + new Date());
      });*/
      };

      /*var modalInstance = $uibModal.open({
        animation: true,
        templateUrl: 'template/cp/storageCreateModal.html',
        controller: 'StorageCreateModalController'
      });

      modalInstance.result.then(function (addItem) {
        $scope.storages.push(addItem);
      }, function () {
        console.log('Modal dismissed at: ' + new Date());
      });
    }*/

    $scope.deleteVolumn = function (item) {
      if (item.mountAppNameArray === undefined || item.mountAppNameArray.length === 0) {
        alertify.confirm("Storage Operation", "确定删除 " + item.name + " 卷?",
          function () {
            storageService.deleteStorage(item).then(function (ret) {
              if (ret.data.ret == true) {
                var _idx = $scope.storages.indexOf(item);
                $scope.storages.splice(_idx, 1);
                alertify.success("delete volume success");
              }
            }, function (ret) {
              alertify.alert('delete volume error', ret.data);
            });
          }, function () {

          }
        );
      } else {
        //may be some time ,the tips can be chinese ,it will be nice
        alertify.alert('delete volume error', 'please umount volume first');
      }
    }

    // $scope.managerVolumn = function(item){
    //     $state.go('cp.storagemanage',{
    //         volname:item.name,
    //         item:item
    //     });
    // }

    $scope.uploadFile = function (item) {

      var modalInstance = $uibModal.open({
        animation: true,
        templateUrl: 'template/cp/uploadFiles.html',
        controller: 'UploadFilesController',
        resolve: {
          item: function () {
            return item;
          }
        }
      });

      modalInstance.result.then(function (ret) {

      }, function (err) {
        //dismiss err flow
        if (err !== 'cancel' && err !== 'backdrop click') {
          alertify.alert('upload error', err);
        }
      });

    }

    $scope.$on('$destroy', function () {
      if (loopTO !== undefined)
        clearTimeout(loopTO);
      isClose = true;
    });

    function _formatStorageList(storagelist) {
      var _ret = storagelist.slice();
      _ret.forEach(function (storageInfo,index) {
              storageService.getStorageDetail(storageInfo.name).then(function (result) {
                  //storageInfo.use =Math.round(parseFloat(result) / parseFloat(storageInfo.size) * 10000 / 100.00);
                  $scope.currentPageStorages[index].use = Math.round(parseFloat(result) / parseFloat(storageInfo.size) * 10000 / 100.00);
                  if(radialIndicatorInstance['perMiniId'+index]) {
                      radialIndicatorInstance['perMiniId' + index].animate($scope.currentPageStorages[index].use);
                  }
              }, function (error) {
                  return error;
              });
        if (storageInfo.mountAppNameArray !== undefined && storageInfo.mountAppNameArray instanceof Array) {
          //old service add new volume after service update
          if (storageInfo.mountAppName !== undefined
            && storageInfo.mountAppName !== ''
            && storageInfo.mountAppNameArray.length !== 0
            && storageInfo.mountAppNameArray.indexOf(storageInfo.mountAppName) === -1)
            storageInfo.mountAppNameArray.push(storageInfo.mountAppName);
          storageInfo.appsMount = storageInfo.mountAppNameArray.join(',');
          storageInfo.status = storageInfo.mountAppNameArray.length === 0 ? 'NOT_USE' : 'USE'
        } else
          storageInfo.appsMount = storageInfo.mountAppName;
      });
      return _ret;
    }
  }
);